package org.news.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.news.web.constant.NotificationConstant;
import org.news.web.domain.Users;
import org.news.web.mapper.UsersMapper;
import org.springframework.stereotype.Service;
import org.news.web.domain.bo.NotificationsBo;
import org.news.web.domain.vo.NotificationsVo;
import org.news.web.domain.Notifications;
import org.news.web.mapper.NotificationsMapper;
import org.news.web.service.INotificationsService;

import java.util.HashSet;
import java.util.List;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 通知功能Service业务层处理
 *
 * @author Gu Ci
 * @date 2024-04-03
 */
@RequiredArgsConstructor
@Service
public class NotificationsServiceImpl implements INotificationsService {

    private final NotificationsMapper baseMapper;

    private final UsersMapper usersMapper;

    /**
     * 查询通知功能
     */
    @Override
    public NotificationsVo queryById(Long notificationId){
        return baseMapper.selectVoById(notificationId);
    }

    /**
     * 查询通知功能列表
     */
    @Override
    public TableDataInfo<NotificationsVo> queryPageList(NotificationsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Notifications> lqw = buildQueryWrapper(bo);
        Page<NotificationsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        /**
         *  通过ids 获取用户名 进行赋予
         */
        if(ObjectUtil.isNotNull(result.getRecords()) && result.getRecords().size() > 0){
//            获取ids
            Set<Long> collect = result.getRecords().stream().map(NotificationsVo::getUserId).collect(Collectors.toSet());
//            获取用户名集合
            List<Users> users = usersMapper.selectList(new LambdaQueryWrapper<Users>().in(Users::getUserId, collect));
//            赋值
            if(ObjectUtil.isNotNull(users) && users.size()>0){
                result.getRecords().forEach(notificationsVo -> {
                    users.stream().forEach(usersItem->{
                        if(usersItem.getUserId() == notificationsVo.getUserId()){
                            notificationsVo.setUsername(usersItem.getUsername());
                        }
                    });
                });
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询通知功能列表
     */
    @Override
    public List<NotificationsVo> queryList(NotificationsBo bo) {
        LambdaQueryWrapper<Notifications> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Notifications> buildQueryWrapper(NotificationsBo bo) {
        LambdaQueryWrapper<Notifications> lqw = Wrappers.lambdaQuery();
        Set<Long> userIds = null;
        if(bo.getUserId() != null){
            lqw.eq(bo.getUserId() != null, Notifications::getUserId, bo.getUserId());
        }else{
            if(StringUtils.isNotBlank(bo.getUsername())){
                List<Users> username = usersMapper.selectList(new QueryWrapper<Users>().like("username", bo.getUsername()));
                if(ObjectUtil.isNotNull(username) && username.size() >0){
                    userIds = username.stream().map(Users::getUserId).collect(Collectors.toSet());
                }else{
//                查询不到用户 给一个查不到的id
                    userIds = new HashSet<>();
                    userIds.add(-1l);
                }
            }
            lqw.in(userIds!= null, Notifications::getUserId, userIds);
        }
        lqw.eq(bo.getNotificationType() != null, Notifications::getNotificationType, bo.getNotificationType());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), Notifications::getContent, bo.getContent());
        lqw.eq(bo.getIsRead() != null, Notifications::getIsRead, bo.getIsRead());
        lqw.eq(bo.getCreationTime() != null, Notifications::getCreationTime, bo.getCreationTime());
        return lqw;
    }

    /**
     * 新增通知功能
     */
    @Override
    public Boolean insertByBo(NotificationsBo bo) {
        Notifications add = MapstructUtils.convert(bo, Notifications.class);
        validEntityBeforeSave(add);
        DFData(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setNotificationId(add.getNotificationId());
        }
        return flag;
    }

    /**
     * 设置默认值
     * @param add
     */
    public void DFData(Notifications add) {
        /**
         * 设置已读状态 默认未读
         */
        add.setIsRead(NotificationConstant.DF_ISREAD);
    }

    /**
     * 修改通知功能
     */
    @Override
    public Boolean updateByBo(NotificationsBo bo) {
        Notifications update = MapstructUtils.convert(bo, Notifications.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Notifications entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除通知功能
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean sendSystemMsg(Long userId, String msg) {

        NotificationsBo notifications = new NotificationsBo();
        notifications.setNotificationType(NotificationConstant.XT_STATUS);
        notifications.setUserId(userId);
        notifications.setContent(msg);
        this.insertByBo(notifications);
        return false;
    }
}
